package com.zd.controller;

import com.zd.service.IUserService;
import io.swagger.annotations.ApiResponse;
import org.springframework.util.StringUtils;
import com.zd.config.Result;
import com.zd.entity.Admin;
import com.zd.entity.LoginEntity;
import com.zd.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @Author TSP
 * @Date 2021/8/22 19:38
 * @ClassName LoginController
 * @Description ：
 */
@Api(tags = "LoginController", description = "用户登录")
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;


    @ApiOperation(value = "成功登陆后返回token")
    @PostMapping("/login")
//    后端@RequestBody注解对应的类在将HTTP的输入流(含请求体)装配到目标类(即：@RequestBody后面的类)时，会根据json字符串中的key来匹配对应实体类的属性，如果匹配一致且json中的该key对应的值符合(或可转换为)
    public Result login(@RequestBody LoginEntity loginEntity, HttpServletRequest request) {
        System.out.println(loginEntity.toString());
        //判断验证码是否符合
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println(captcha);
        if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(loginEntity.getCaptcha()) || !captcha.equalsIgnoreCase(loginEntity.getCaptcha())) {
            return Result.error("验证码输入错误,请重新输入！");
        }
        //判断身份调用相关的登录方法
        return userService.login(loginEntity.getUsername(), loginEntity.getPassword());
    }


    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/login/info")
    public Result getLoginInfo(Principal principal) {
//        , @RequestParam(name = "role", required = true) String role
        System.out.println(this + ":" + principal.toString());
        String role = "admin";
        if (principal == null) {
            return Result.error("未登录");
        }
        String username = principal.getName();
        //根据身份去获取登录信息
        //需要做健壮性代码补充

        return Result.success("当前登录管理员信息");
    }

    @ApiOperation(value = "登出")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //将成功登出逻辑交给前端丢弃授权token来实现
        return Result.success("退出登陆成功!");
    }

}
